package com.example.demo.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class ReceiveNewsTest {
    public static void main(String[] args) throws Exception {
        ReceiveNewsTest test = new ReceiveNewsTest();
        test.TestToken();
    }

    public String getXmlData() {
        // 定义动态变量
        String token = "your_token"; // TODO 待处理
        String timestamp = System.currentTimeMillis() + "";
        String cmsNode = "14641"; // 增加到的栏目编号，可以有多个栏目 166419,178330,14645
        String cmsFile = "0"; //如果节目未添加到流程系统里，值为0.如果已经添加到流程系统里，值为节目的在流程系统里的CMSID

        String indexId = "2724129"; // 节目在视频管理系统中的编号
        String title = "股市大跌"; // 节目标题 比如意大利：泡泡魔术师  打造“我在泡泡中
        String cmspublishtime1 = "1433992252694"; // 添加到流程系统的时间 创建时间
        String publishDate = "1433990275000"; // 发布时间
        String isTVM = "0"; // 节目的来源是否是天脉  0 表示 是，其他表示不是
        String keyword = "信用卡"; // 节目的关键词
        String templateId = "113482"; // 使用的模板编号
        String description = "信用卡消费"; // 描述
        String author = "张yy"; // 作者 【选填】
        String source = "趣看"; //来源 下拉
        String authorId = "300847"; // 作者id
        String editor = "张yy"; // 责编 【必填】
        String videoUrl = "/pvservice/xml/2015/6/11/4020af82-e12c-4e35-a46f-d906e2b0744b.xml?adtags="; // 视频文件 【带域名链接】
        String videolength = "40050"; // 视频长度
        String programtext = ""; // 正文
        String picUrl = "http://japflv.people.com.cn/videofile2/pvmsimage/2015/6/11/weiqingcheng_22985e6604fb5481d7f0b4d04d51daca.jpg"; // 节目图片
        String cmspublishtime2 = "1433992252707"; // 签发到流程系统的时间 【提交时间】

        // 拼接 XML 字符串
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>"
                + "<mmscontent>"
                + "<token>" + token + "</token>"
                + "<timestamp>" + timestamp + "</timestamp>"
                + "<contenttype>news</contenttype>"
                + "<operationtype>add</operationtype>"
                + "<target>"
                + "<cmsnode><![CDATA["+cmsNode+"]]></cmsnode>"
                + "<cmsfile><![CDATA["+cmsFile+"]]></cmsfile>"
                + "</target>"
                + "<content>"
                + "<contentinfo>"
                + "<indexid><![CDATA[" + indexId + "]]></indexid>"
                + "<tableid><![CDATA[0]]></tableid>"
                + "<title><![CDATA[" + title + "]]></title>"
                + "<cmspublishtime><![CDATA[" + cmspublishtime1 + "]]></cmspublishtime>"
                + "<publishDate>" + publishDate + "</publishDate>"
                + "<isTVM><![CDATA[" + isTVM + "]]></isTVM>"
                + "<keyword><![CDATA[" + keyword + "]]></keyword>"
                + "<templateid>" + templateId + "</templateid>"
                + "<description><![CDATA[" + description + "]]></description>"
                + "</contentinfo>"
                + "<extrainfo>"
                + "<shouldernote><![CDATA[]]></shouldernote>"
                + "<subtitle><![CDATA[]]></subtitle>"
                + "<author><![CDATA[" + author + "]]></author>"
                + "<source><![CDATA["+source+"]]></source>"
                + "<authorid><![CDATA[" + authorId + "]]></authorid>"
                + "<editor><![CDATA[" + editor + "]]></editor>"
                + "<contentvideo>"
                + "<video name=\"NAME\"><![CDATA[" + videoUrl + "]]></video>"
                + "<videolength>" + videolength + "</videolength>"
                + "</contentvideo>"
                + "<programtext><![CDATA[<p>"+programtext+"</p>]]></programtext>"
                + "<programpicture>"
                + "<pic name=\"NAME\"><![CDATA[" + picUrl + "]]></pic>"
                + "</programpicture>"
                + "<cmspublishtime><![CDATA[" + cmspublishtime2 + "]]></cmspublishtime>"
                + "</extrainfo>"
                + "</content>"
                + "</mmscontent>";

        System.out.println(xml);
        return  xml;
    };

    public void TestToken() throws IOException {
        String xml = "";
        String secret = "8SbKwWjzrY43X/QS3KF2HQ==";
        String public_key = "jxYoysLtr=jUGfCeTlrhqMA=";    //主站约定
//        String public_key = " wxUgtsLot=iPGfCfTlwnqWT=";  //地方约定
        String author_id = "104453";

        Long timestamp = System.currentTimeMillis();
        Map<String, String[]> params = new HashMap<String, String[]>();
        params.put("public_key", new String[]{public_key});
        params.put("author_id", new String[]{author_id});
        params.put("timestamp", new String[]{timestamp.toString()});
        String token = generateToken(secret, params);
        System.out.println("token:" + token);
        System.out.println("timestamp:" + timestamp);
        xml = "<?xml version=\"1.0\" encoding=\"GBK\"?> "
                +"<mmscontent>" + "<token>" + token + "</token>" + "<timestamp>" + timestamp + "</timestamp>" +

                "<contenttype>news</contenttype><operationtype>add</operationtype><target><cmsnode><![CDATA[457645]]></cmsnode><cmsfile><![CDATA[0]]></cmsfile></target><content><contentinfo><indexid><![CDATA[2724129]]></indexid><tableid><![CDATA[0]]></tableid><title><![CDATA[股市大跌]]></title><cmspublishtime><![CDATA[1433992252694]]></cmspublishtime><publishDate>1433990275000</publishDate><isTVM><![CDATA[0]]></isTVM><keyword><![CDATA[信用卡]]></keyword><templateid>120669</templateid><description><![CDATA[信用卡消费]]></description></contentinfo><extrainfo><shouldernote><![CDATA[]]></shouldernote><subtitle><![CDATA[]]></subtitle><author><![CDATA[张yy]]></author><source><![CDATA[]]></source><authorid><![CDATA[300847]]></authorid><editor><![CDATA[张yy]]></editor><contentvideo><video name=\"NAME\"><![CDATA[/pvservice/xml/2015/6/11/4020af82-e12c-4e35-a46f-d906e2b0744b.xml?adtags=]]></video><videolength>40050</videolength></contentvideo><programtext><![CDATA[<p></p>]]></programtext><programpicture><pic name=\"NAME\"><![CDATA[http://japflv.people.com.cn/videofile2/pvmsimage/2015/6/11/weiqingcheng_22985e6604fb5481d7f0b4d04d51daca.jpg]]></pic></programpicture><cmspublishtime><![CDATA[1433992252707]]></cmspublishtime></extrainfo></content></mmscontent>";

        xml = getXmlDataNew();
        xml = getXmlDataNew2(token,timestamp);
        xml = getXmlDataNew3(token,timestamp.toString());
        System.out.println(xml);

        System.out.println("MemberCmsController--->sendXmlPostRequest--->xmlString:"+xml);
        // 发送POST请求
        String response = sendPostRequest("http://10.3.39.93:8930/tv2cms", xml);

        System.out.println("MemberCmsController--->sendXmlPostRequest--->response:"+response);

//        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
//        factory.setServiceClass(ReceiveNewsInterface.class);
//        //	factory.setAddress("http://localhost:8888/services/ReceiveNews");
////        factory.setAddress("http://localhost:8888/services/ReceiveNews");
//        factory.setAddress("http://10.3.39.93:8930/tv2cms");
//        ReceiveNewsInterface service = (ReceiveNewsInterface) factory.create();
//        System.out.print("--------------- start----------------");
//        String str = service.receiveNews(xml);
//        System.out.println("str:"+str);
//        System.out.println("---------------end----------------");
    }

    private static String sendPostRequest(String url, String xmlData) throws IOException {
        HttpURLConnection conn = null;
        try {
            URL requestUrl = new URL(url);
            conn = (HttpURLConnection) requestUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/xml; charset=GBK");
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = xmlData.getBytes("GBK");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "GBK"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    return response.toString();
                }
            } else {
                throw new IOException("HTTP error code: " + responseCode);
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    private String getXmlDataNew3(String token, String timestamp) {
        return "<?xml version=\"1.0\" encoding=\"GBK\"?><mmscontent><token>"+token+"</token><timestamp>"+timestamp+"</timestamp><contenttype>news</contenttype><operationtype>add</operationtype><target><cmsnode><![CDATA[457645]]></cmsnode><cmsfile><![CDATA[0]]></cmsfile></target><content><contentinfo><indexid><![CDATA[1741760498710263]]></indexid><tableid><![CDATA[0]]></tableid><title><![CDATA[2222.mp4]]></title><cmspublishtime><![CDATA[1742270558552]]></cmspublishtime><publishDate>"+timestamp+"</publishDate><isTVM><![CDATA[0]]></isTVM><keyword><![CDATA[测试]]></keyword><templateid>120669</templateid><description><![CDATA[测试发布呀]]></description></contentinfo><extrainfo><shouldernote><![CDATA[测试发布]]></shouldernote><subtitle><![CDATA[]]></subtitle><author><![CDATA[媒资系统]]></author><source><![CDATA[趣看]]></source><authorid><![CDATA[104453]]></authorid><editor><![CDATA[test01]]></editor><contentvideo><video name=\"NAME\"><![CDATA[https://video.people.cn/upload/vod/user1735982106105323/1741760498710263/origin.mp4]]></video><videolength>40050</videolength></contentvideo><programtext><![CDATA[<p><p>测试</p></p>]]></programtext><programpicture><pic name=\"NAME\"><![CDATA[https://video.people.cn/userUpload/1735982106105323/1741760498710263/picture/prescreen.png]]></pic></programpicture><cmspublishtime><![CDATA["+timestamp+"]]></cmspublishtime></extrainfo></content></mmscontent>";
    }

    private String getXmlDataNew2(String token, Long timestamp) {

        return "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<mmscontent>\n" +
                "    <token>"+token+"</token>\n" +
                "    <timestamp>"+timestamp+"</timestamp>\n" +
                "    <contenttype>news</contenttype>\n" +
                "    <operationtype>add</operationtype>\n" +
                "    <target>\n" +
                "        <cmsnode><![CDATA[457645]]></cmsnode>\n" +
                "        <cmsfile><![CDATA[0]]></cmsfile>\n" +
                "    </target>\n" +
                "    <content>\n" +
                "        <contentinfo>\n" +
                "            <indexid><![CDATA[1740539559428148]]></indexid>\n" +
                "            <tableid><![CDATA[0]]></tableid>\n" +
                "            <title><![CDATA[意大利：泡泡魔术师  打造“我在泡泡中”]]></title>\n" +
                "            <cmspublishtime><![CDATA[1741741986841]]></cmspublishtime>\n" +
                "            <publishDate>1292336308000</publishDate>\n" +
                "            <isTVM><![CDATA[0]]></isTVM>\n" +
                "            <keyword><![CDATA[罗马]]></keyword>\n" +
                "            <templateid>120669</templateid>\n" +
                "            <description><![CDATA[]]></description>\n" +
                "        </contentinfo>\n" +
                "        <extrainfo>\n" +
                "            <shouldernote><![CDATA[]]></shouldernote>\n" +
                "            <subtitle><![CDATA[]]></subtitle>\n" +
                "            <author><![CDATA[]]></author>\n" +
                "            <authorid><![CDATA[104453]]></authorid>\n" +
                "            <source><![CDATA[央视网]]></source>\n" +
                "            <editor><![CDATA[樊英武]]></editor>\n" +
                "            <contentvideo>\n" +
                "                <video name=\"NAME\"><![CDATA[http://recordcdn-sz.qukanvideo.com/upload/vod/user1720665496623010/1740539559428148/origin.mp4]]></video>\n" +
                "                <videolength>40050</videolength>\n" +
                "            </contentvideo>\n" +
                "            <programtext><![CDATA[labore adipisicing minim velit Lorem]]></programtext>\n" +
                "            <programpicture>\n" +
                "                <pic name=\"NAME\"><![CDATA[http://recordcdn-sz.qukanvideo.com/userUpload/1720665496623010/1740539559428148/picture/prescreen.png]]></pic>\n" +
                "            </programpicture>\n" +
                "            <cmspublishtime><![CDATA[1741741986841]]></cmspublishtime>\n" +
                "        </extrainfo>\n" +
                "    </content>\n" +
                "</mmscontent>";
    }

    private String getXmlDataNew() {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<mmscontent>\n" +
                "    <token>1cfdde4aaf488adbc89f9ae835cb86eb</token>\n" +
                "    <timestamp>1557818598764</timestamp>\n" +
                "    <!-- 固定值news -->\n" +
                "    <contenttype>news</contenttype>\n" +
                "    <!-- 有四种取值add,delete,update,updatesummary分别对应四种操作增加节目，删除节目，修改节目信息，更新摘要 -->\n" +
                "    <operationtype>add</operationtype>\n" +
                "    <target>\n" +
                "        <!-- 增加到的栏目编号，可以有多个栏目 -->\n" +
                "        <cmsnode><![CDATA[457645]]></cmsnode>\n" +
                "        <!-- 如果节目未添加到流程系统里，值为0.如果已经添加到流程系统里，值为节目的在流程系统里的CMSID -->\n" +
                "        <cmsfile><![CDATA[0]]></cmsfile>\n" +
                "    </target>\n" +
                "    <content>\n" +
                "        <contentinfo>\n" +
                "            <!-- 节目在视频管理系统中的编号 -->\n" +
                "            <indexid><![CDATA[1740539559428148]]></indexid>\n" +
                "            <!-- 固定值 0 -->\n" +
                "            <tableid><![CDATA[0]]></tableid>\n" +
                "            <!-- 节目标题 -->\n" +
                "            <title><![CDATA[意大利：泡泡魔术师  打造“我在泡泡中”]]></title>\n" +
                "            <!-- 添加到流程系统的时间 -->\n" +
                "            <cmspublishtime><![CDATA[1292372328503]]></cmspublishtime>\n" +
                "            <!-- 节目的发布时间 -->\n" +
                "            <publishDate>1292336308000</publishDate>\n" +
                "            <!-- 节目的来源是否是天脉  0 表示 是，其他表示不是-->\n" +
                "            <isTVM><![CDATA[0]]></isTVM>\n" +
                "            <!-- 节目的关键词 -->\n" +
                "            <keyword><![CDATA[罗马]]></keyword>\n" +
                "            <!-- 使用的模板编号 -->\n" +
                "            <templateid>120669</templateid>\n" +
                "            <!-- 描述  -->\n" +
                "            <description><![CDATA[]]></description>\n" +
                "        </contentinfo>\n" +
                "        <extrainfo>\n" +
                "            <!-- 肩标题 -->\n" +
                "            <shouldernote><![CDATA[]]>\n" +
                "            </shouldernote>\n" +
                "            <!-- 副标题 -->\n" +
                "            <subtitle><![CDATA[]]>\n" +
                "            </subtitle>\n" +
                "            <!-- 作者 -->\n" +
                "            <author><![CDATA[]]>\n" +
                "            </author>\n" +
                "            <!-- 来源 -->\n" +
                "            <source><![CDATA[央视网]]></source>\n" +
                "            <!-- 责编 -->\n" +
                "            <editor><![CDATA[樊英武]]></editor>\n" +
                "            <!-- 视频文件 -->\n" +
                "            <contentvideo>\n" +
                "                <video name=\"NAME\"><![CDATA[/pvservice/xml/2010/12/15/e97ddc74-ce9e-4e10-abb4-9ace6780be51.ptv]]></video>\n" +
                "            </contentvideo>\n" +
                "            <!-- 正文 -->\n" +
                "            <programtext><![CDATA[]]>\n" +
                "            </programtext>\n" +
                "            <!-- 节目图片 -->\n" +
                "            <programpicture>\n" +
                "                <pic name=\"NAME\"><![CDATA[http://flv.people.com.cn/pvms1/News/JPGPEOPLE/CCTV1/2010/12/14/CCTV1_20101214_221619563_517885_128797.jpg]]></pic>\n" +
                "            </programpicture>\n" +
                "            <!-- 签发到流程系统的时间 -->\n" +
                "            <cmspublishtime><![CDATA[1292372328503]]></cmspublishtime>\n" +
                "        </extrainfo>\n" +
                "    </content>\n" +
                "</mmscontent>";
    }

    /**  2019-04-05 caiweihui add
     * 生成接口签名
     *
     * @param secret 分配密钥
     * @param params URL参数列表
     * @return
     */

    public  String generateToken(String secret, Map<String, String[]> params) {
        StringBuilder builder = new StringBuilder();
        builder.append(secret).append("&");

        Map<String, String[]> cloneMap = new HashMap<String, String[]>(params);
        cloneMap.remove("token");

        String[] keys = sortKeys(cloneMap.keySet().toArray(new String[0]));
        StringBuilder kv = new StringBuilder();

        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            String[] values = params.get(key);
            if (values != null && values.length > 0) {
                kv.append(key).append("=").append(values[0]);
            }

            if (i < (keys.length - 1)) {
                kv.append("&");
            }
        }

        if (kv.length() > 0) {
            builder.append("&").append(encode(kv.toString()));
        }

        return DigestUtils.md5Hex(builder.toString());
    }


    /**
     * key排序
     * @param keys key数组
     * @return 排序后的key数组
     */

    public  String[] sortKeys(String[] keys) {
        for (int i = 0; i < keys.length - 1; i++) {
            for (int j = i + 1; j < keys.length; j++) {
                String temp = "";

                if (keys[i].compareTo(keys[j]) > 0) {
                    temp = keys[j];
                    keys[j] = keys[i];
                    keys[i] = temp;
                }
            }
        }
        return keys;
    }

    /**
     * UTF-8编码
     * @param value 待编码数据
     * @return 编码后数据
     */

    public   String encode(String value) {
        String result = null;

        try {
            result = URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            result = "";
        }

        return result;
    }
}
